package menu

import (
	"context"
	"myapp/internal/dao"
	"myapp/internal/model/do"
	"myapp/internal/model/entity"
	"myapp/internal/service"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/gtime"
)

type sAdminMenu struct{}

func init() {
	service.RegisterAdminMenu(New())
}

func New() *sAdminMenu {
	return &sAdminMenu{}
}

func (u *sAdminMenu) Create(ctx context.Context, in *entity.AdminMenu) (int64, error) {
	var err error
	if err = u.checkAdminMenuMenu(ctx, in.Title, 0); err != nil {
		return 0, err
	}
	result, err := dao.AdminMenu.Ctx(ctx).Data(do.AdminMenu{
		Title:      in.Title,     // 菜单名称
		Pid:        in.Pid,       // 父级id
		Level:      in.Level,     // 层级
		Url:        in.Url,       // 访问地址
		Hide:       in.Hide,      // 是否隐藏
		Status:     in.Status,    // 状态:1启用
		IconClass:  in.IconClass, // 小图标的样式
		SortNum:    in.SortNum,   // 菜单排序
		CreateTime: gtime.Now(),
	}).Insert()

	if err != nil {
		return 0, err
	}
	id, err := result.LastInsertId()
	return id, err
}

// 批量获取菜单
func (u *sAdminMenu) GetMenus(ctx context.Context, ids []uint) ([]*entity.AdminMenu, error) {
	menus := make([]*entity.AdminMenu, 0, 64)
	err := dao.AdminMenu.Ctx(ctx).WhereIn("id", ids).Limit(1000).Scan(&menus)
	if err != nil {
		return nil, err
	}

	return menus, err
}

// 检查用户名是否存在, 并排除自己
func (u *sAdminMenu) checkAdminMenuMenu(ctx context.Context, title string, id uint) error {
	if title == "" {
		return gerror.New("title不能为空")
	}
	m := dao.AdminMenu.Ctx(ctx).Where("title", title)
	if id > 0 {
		m = m.WhereNot("id", id)
	}
	count, err := m.Count()
	if err != nil {
		return err
	}
	if count > 0 {
		return gerror.New("此菜单已经添加")
	}
	return nil
}
